package com.test;

import com.mongodb.Block;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
import org.bson.BSONObject;
import org.bson.Document;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class App {
    public static void main(String[] args) {
        connectPost();
//        connectMongoDB();
    }

    private static void connectPost() {

        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager
                    .getConnection("jdbc:postgresql://localhost:5432/postgres",
                            "postgres", "postgres");
            stmt = c.createStatement();
            //导入数据
//            List<String> carsFiles = getFiles("C:\\Car");
//            for (String path : carsFiles) {
//                List<Car> cars = readFile1(path);
//                for (Car car : cars) {
//                    String sql = "INSERT INTO car (name,time,lng,lat) "
//                            + "VALUES ('" + car.getName() + "', '" + car.getTime() + "'," + car.getLng() + "," + car.getLat() + " );";
//                    stmt.executeUpdate(sql);
//                }
//            }
//            c.commit();
// 读取数据
            ResultSet rs = stmt.executeQuery("select lng,lat from car");
            List<double[]> list=new ArrayList<>();
            while(rs.next()){
                double lng = rs.getDouble("lng");
                double lat = rs.getDouble("lat");
                double[] point={lng,lat};
                list.add(point);
            }
            rs.close();
            stmt.close();
            c.close();
            double[][] points=new double[list.size()][2];

            for (int i = 0; i <list.size() ; i++) {
                points[i]=list.get(i);
            }
            KmeansTest.test(points,40);
//            Kcluster kcluster=new Kcluster();
//            kcluster.productPoint(points,20);
//            kcluster.movecore();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Opened database successfully");

    }

    private static void connectMongoDB() {
        try {
            // 连接到 mongodb 服务
            MongoClient mongoClient = new MongoClient("localhost", 27017);

            // 连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("Car");
            System.out.println("Connect to database successfully");
            MongoCollection<DBObject> collection = mongoDatabase.getCollection("cars", DBObject.class);
//导入数据
//            List<String> carsFiles = getFiles("C:\\Car");
//            for (String Car : carsFiles) {
//                List<DBObject> carInfos=readFile(Car);
//                collection.insertMany(carInfos);
//            }
            //读取数据
            FindIterable<DBObject> iter = collection.find();
            iter.forEach(new Block<DBObject>() {
                @Override
                public void apply(DBObject dbObject) {
                    System.out.println(dbObject.toString());
                }
            });


        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    /**
     * 获取文件列表
     *
     * @param parentPath
     * @return
     */
    private static List<String> getFiles(String parentPath) {
        List<String> list = new ArrayList<>();
        File file = new File(parentPath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                    } else {
                        list.add(file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return list;
    }

    /**
     * 读取单个文件
     *
     * @param path
     * @return
     */
    private static List<DBObject> readFile(String path) {
        List<DBObject> dbObjects = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行

                String[] sourceStrArray = s.split(",");
                String json = "{" +
                        "'name':'" + sourceStrArray[0] + "'," +
                        "'time':'" + sourceStrArray[1] + "'," +
                        "'lng':'" + sourceStrArray[2] + "'," +
                        "'lat':'" + sourceStrArray[3] + "'" +
                        "}";
                DBObject bson = (DBObject) JSON.parse(json);
                dbObjects.add(bson);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return dbObjects;
    }

    private static List<Car> readFile1(String path) {
        List<Car> cars = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行

                String[] sourceStrArray = s.split(",");
                Car car = new Car();
                car.setName(sourceStrArray[0]);
                car.setTime(sourceStrArray[1]);
                car.setLng(sourceStrArray[2]);
                car.setLat(sourceStrArray[3]);
                cars.add(car);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return cars;
    }
}
